#ifndef _RQ_CP_HPP_
#define _RQ_CP_HPP_

#include <vector>
#include <pthread.h>
#include "sem.hpp"

const int g_default_num = 5;

template <class T>
class RingQueue
{
public:
    RingQueue(int default_num = g_default_num)
        :num_(default_num), ring_queue_(default_num), c_step(0), p_step(0),space_sem_(default_num),data_sem_(default_num)
    {
        pthread_mutex_init(&clock, nullptr);
        pthread_mutex_init(&plock, nullptr);
    }

    void push(const T &in)
    {
        space_sem_.p();
        pthread_mutex_lock(&plock);
        ring_queue_[p_step++] = in;
        p_step %= num_;
        pthread_mutex_unlock(&plock);
        data_sem_.v();
    }

    void pop(T *out)
    {
        data_sem_.p();
        pthread_mutex_lock(&clock);
        *out = ring_queue_[c_step++];
        c_step%=num_;
        pthread_mutex_unlock(&clock);
        space_sem_.v();
    }
    ~RingQueue()
    {
        pthread_mutex_destroy(&clock);
        pthread_mutex_destroy(&plock);
    }

private:
    std::vector<T> ring_queue_;
    int num_;
    int c_step;
    int p_step;
    Sem space_sem_;
    Sem data_sem_;
    pthread_mutex_t clock;
    pthread_mutex_t plock;
};

#endif